#include "CWindow.h"
#include "Managers/DataManager.h"

#include "CStatusBar.h"

#include <QApplication>
#include <QDateTime>
#include <QMenuBar>
#include <QPainter>
#include <QStyle>
#include <QToolButton>
#include <QWindowStateChangeEvent>

CWindow::CWindow(QWidget *parent) : CTopWidget(parent) {
    init();
}

CWindow::~CWindow() {
}

void CWindow::reloadStrings() {
}

void CWindow::init() {
    m_titleBar = new CWindowBar();
    m_titleBar->setObjectName("window-bar");

    m_layout->insertWidget(0, m_titleBar);

    m_statusBar = new CStatusBar();
    m_statusBar->setObjectName("window-status-bar");

    m_layout->addWidget(m_statusBar);

    connect(m_titleBar, &CWindowBar::minRequested, this, &CWindow::handleMinimize);
    connect(m_titleBar, &CWindowBar::maxRequested, this, &CWindow::handleMaximize);
    connect(m_titleBar, &CWindowBar::closeRequested, this, &CWindow::handleClose);

    Q_TR_NOTIFY(CWindow)
}

QMenuBar *CWindow::menuBar() const {
    return m_titleBar->menuBar();
}

void CWindow::setMenuBar(QMenuBar *menuBar) {
    m_titleBar->setMenuBar(menuBar);
}

QStatusBar *CWindow::statusBar() const {
    return m_statusBar;
}

void CWindow::setStatusBar(QStatusBar *statusBar) {
    auto *oldItem = m_layout->replaceWidget(m_statusBar, statusBar);
    delete oldItem;
    delete m_statusBar;
    m_statusBar = statusBar;
}

void CWindow::handleMinimize() {
    if (windowState() != Qt::WindowMinimized) {
        setWindowState(Qt::WindowMinimized);
    }
}

void CWindow::handleMaximize() {
    if (windowState() == Qt::WindowNoState) {
        setWindowState(Qt::WindowMaximized);
    } else {
        setWindowState(Qt::WindowNoState);
    }
}

void CWindow::handleClose() {
    close();
}

bool CWindow::isMouseOnCaption() const {
   return m_titleBar->isMouseFree();
}

bool CWindow::isNative() const {
    return m_titleBar->barVisible();
}

void CWindow::setNative(bool value) {
    m_titleBar->setBarVisible(value);
}

void CWindow::windowTitleChangeEvent(QEvent *event) {
    QString title = windowTitle();
    m_titleBar->setWindowTitle(title);
    Q_UNUSED(event)
}

void CWindow::changeEvent(QEvent *event) {
    if (event->type() == QEvent::WindowStateChange) {
        m_titleBar->reloadMaxButtonState();
    }
    CTopWidget::changeEvent(event);
}
